/**
 * 在这里定义和用户相关的路由处理函数，供 /api/score.js 模块进行调用
 */
const { handleQuery } = require('../db/index')
const { blob2String } = require('../utils/index')
// 单添加
exports.add = async (req, res) => {
  const addStr = 'insert into score set ?'
  const updateStr = 'update score set date = ?,name = ?,rightNum = ?,testMinute = ?,totalNum = ?,type = ? where id = ?'
  const { id, date, name, rightNum, testMinute, totalNum, type } = req.body
  delete req.body.id
  const params = [date, name, rightNum, testMinute, totalNum, type, id]
  try {
    const mid = await handleQuery(!id ? addStr : updateStr, !id ? req.body : params)
    res.send({
      code: 200,
      data: !id ? '添加成功' : '更新成功',
      id: id || mid.insertId
    })
  } catch (err) {
    res.send({
      code: 0,
      data: err
    })
  }
}
// 批量导入
exports.batchAdd = async (req, res) => {
  const addStr = 'insert into score (date, name, rightNum, testMinute, totalNum, type) values '
  const mid = []
  req.body.forEach(item => {
    const { date, name, rightNum, testMinute, totalNum, type } = item
    mid.push(`(${date},'${name}',${rightNum},${testMinute},${totalNum},'${type}')`)
  })
  const str = mid.join(',')
  try {
    await handleQuery(addStr + str + ';')
    res.send({
      code: 200,
      data: '导入成功'
    })
  } catch (err) {
    res.send({
      code: 0,
      data: err
    })
  }
}
// 接接查询字符串
function getQueryString (params) {
  const { date, type, name, testMinute } = params
  const mid = []
  if (name) {
    mid.push([`score.name like '%${name}%'`, `or user.nickname like '%${name}%'`])
  }
  if (type) {
    mid.push(['type', `= '${type}'`])
  }
  if (testMinute) {
    mid.push(['testMinute', `= '${testMinute}'`])
  }
  if (date?.length) {
    const [start, end] = date
    const startNum = new Date(start).getTime()
    const endNum = new Date(end).getTime() + 86400000
    mid.push(['date', `between ${startNum} and ${endNum}`])
  }
  return mid.length ? 'where ' + mid.map(item => item.join(' ')).join(' and ') : ''
}
// 列表查询
exports.list = async (req, res) => {
  const { pageSize, currentPage, prop, order } = req.body
  const str = getQueryString(req.body)
  const orderStr = (prop && order) ? ` order by ${prop} ${order === 'ascending' ? 'asc' : 'desc'} ` : ''
  const sqlStr = 'select score.id, score.name,score.date,score.rightNum,score.totalNum,score.type,score.testMinute,user.avatar,user.nickName from score left join user on score.name = user.name ' + str + orderStr + ' limit ?,? '
  const params = [(currentPage - 1) * pageSize, pageSize]
  try {
    const promiseArr = []
    let results = []
    let total = []
    const mid1 = handleQuery(sqlStr, params).then(res => {
      res.forEach((item) => {
        blob2String(item)
      })
      results = res
    })
    const mid2 = handleQuery('select count(*) as total from score left join user on score.name = user.name ' + str, []).then(res => {
      total = res
    })
    promiseArr.push(mid1, mid2)
    Promise.all(promiseArr).then(() => {
      res.send({
        message: '查询成功',
        code: 200,
        data: results,
        total: total[0].total
      })
    })
  } catch (error) {
    res.send(error)
  }
}
// 删除成绩
exports.delete = (req, res) => {
  const sqlStr = `delete from score where id in (${req.body.id.join(',')})`
  handleQuery(sqlStr, []).then(results => {
    res.send({
      code: 200,
      data: results
    })
  }).catch(err => {
    res.send({
      code: 0,
      data: err
    })
  })
}
// 修改头像或昵称
exports.avatar = (req, res) => {
  const { avatar, nickName, name } = req.body
  const sqlStr = `update user set ${avatar ? 'avatar' : 'nickname'} = ? where name = ?`
  handleQuery(sqlStr, [avatar ?? nickName, name]).then(results => {
    res.send({
      code: 200,
      data: results
    })
  }).catch(err => {
    res.send({
      code: 0,
      data: err
    })
  })
}

